﻿namespace Wolfpack.Contrib.Checks.Drive
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using Wolfpack.Core.Interfaces.Entities;
    using Wolfpack.Core.Interfaces;
    using Wolfpack.Core;
    using System.IO;

    public class SpaceCheckConfig : PluginConfigBase
    {
        public string Drive { get; set; }
        public string Threshold { get; set; }
    }

    public class SpaceCheck : IHealthCheckPlugin
    {
        private readonly SpaceCheckConfig myConfig;

        /// <summary>
        /// default ctor
        /// </summary>
        public SpaceCheck(SpaceCheckConfig config)
        {
            this.myConfig = config;
        }

        public Status Status { get; set; }


        public PluginDescriptor Identity
        {
            get
            {
                return new PluginDescriptor
                {
                    Description = "Free space check.",
                    Name = this.myConfig.FriendlyId,

                    TypeId = new Guid("93092669-6995-427a-84CF-EF4F030AB181")

                };
            }
        }

        public void Initialise()
        {
        }

        public void Execute()
        {
            Logger.Debug("Running HealthCheck: {0}, Drive: {1}, Threshold: {2}", myConfig.FriendlyId, myConfig.Drive, myConfig.Threshold);

            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                if (drive.IsReady && drive.Name.Contains(myConfig.Drive.ToUpper()))
                {
                    if (Convert.ToInt64(drive.TotalFreeSpace) < Convert.ToInt64(myConfig.Threshold))
                    {
                        this.Publish(drive.TotalFreeSpace);
                    }

                    break;
                }
            }

            Logger.Debug("Done checking free space.");
        }

        public void Publish(long totalFreeSpace)
        {
            try
            {
                var result = new HealthCheckData
                {
                    Identity = this.Identity,
                    Result = false,
                    Info = Convert.ToString(totalFreeSpace),
                    Tags = myConfig.Drive
                };

                result.Properties = new ResultProperties
                {
                    { "DriveLetter", myConfig.Drive},
                    { "FreeSpace", Convert.ToString(totalFreeSpace)},
                    { "Threshold", myConfig.Threshold}
                };

                Messenger.Publish(result);

                Logger.Debug("Publishing TotalFreeSpace {0} < {1} Threshold", totalFreeSpace, myConfig.Threshold);

            }
            catch (Exception ex)
            {
                Logger.Error("Free Space error during publish: {0}", ex.Message);
            }

        }
    }
}